package com.video.demo.service.impl;


import com.video.demo.domain.TaskEntity;
import com.video.demo.service.OutHandler;
import com.video.demo.service.TaskHandler;
import org.springframework.stereotype.Service;

import java.io.IOException;

/**
 * 任务处理实现
 * @author lmc
 * @since jdk1.7
 * @version 2020-05-24
 */
@Service
public class TaskHandlerImpl implements TaskHandler {
	private Runtime runtime = null;
 

	public TaskEntity process(String id, String command) {
		Process process = null;
		OutHandler outHandler = null;
		TaskEntity tasker = null;
		try {
			if (runtime == null) {
				runtime = Runtime.getRuntime();
			}
			process = runtime.exec(command);
//			try {
//
//				System.out.println(process.waitFor()+"----------------------------");
//			} catch (InterruptedException e) {
//				e.printStackTrace();
//			}
			outHandler = new OutHandler(process.getErrorStream(), id);
			outHandler.start();
			tasker = new TaskEntity(id, process, outHandler);
		} catch (IOException e) {
			stop(outHandler);
			stop(process);
			return null;
		}
		return tasker;
	}
 

	public boolean stop(Process process) {
		if (process != null && process.isAlive()) {
			process.destroy();
			return true;
		}
		return false;
	}
 

	public boolean stop(Thread outHandler) {
		if (outHandler != null && outHandler.isAlive()) {
			outHandler.stop();
			outHandler.destroy();
			return true;
		}
		return false;
	}
 

	public boolean stop(Process process, Thread thread) {
		boolean ret;
		ret=stop(thread);
		ret=stop(process);
		return ret;
	}
}
 
